from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
from django_redis import get_redis_connection
from utils.captcha import captcha


class ImageCode():
    # 随机字母:
    def rndChar(self):
        return chr(random.randint(65, 90))

    # 随机颜色1:
    def rndColor(self):
        return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)

    # 随机颜色2:
    def rndColor2(self):
        return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)

    @classmethod
    def generate_image_code(cls, uuid_code):
        # 生成随机数
        code = cls().rndChar() + cls().rndChar() + cls().rndChar() + cls().rndChar()
        # 设置图片宽高 240 x 60:
        width = 60 * 4
        height = 60
        image = Image.new('RGB', (width, height), (255, 255, 255))
        # 创建Font对象:
        font = ImageFont.truetype('./utils/HyFJustAKiss-2.ttf', 42)
        # 创建Draw对象:
        draw = ImageDraw.Draw(image)
        # 填充每个像素:
        for x in range(width):
            for y in range(height):
                draw.point((x, y), fill=cls().rndColor())
        # 输出文字:
        for t in range(4):
            draw.text((60 * t + 10, 10), code[t], font=font, fill=cls().rndColor2())
        # 模糊:
        image = image.filter(ImageFilter.BLUR)
        cls().set_image_code_expire(uuid_code, code)
        return image

    @classmethod
    def generate_image_by_captcha(cls, uuid_code):
        code, image = captcha.generate_captcha()
        cls().set_image_code_expire(uuid_code, code)
        return image

    def set_image_code_expire(self, uuid_code, code, second=60*5):
        verify_redis = get_redis_connection('verify_code')
        verify_redis.setex(f'img_code_{uuid_code}', second, code)
